package com.itheima.appserver.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.dubbo.config.annotation.Reference;

import com.itheima.appserver.excepiton.MyException;
import com.itheima.appserver.interceptor.UserThreadLocal;
import com.itheima.commons.autoconfig.template.OssTemplate;
import com.itheima.commons.model.domain.User;
import com.itheima.commons.model.domain.UserInfo;
import com.itheima.commons.model.mongo.Voice;
import com.itheima.commons.model.vo.ErrorResult;
import com.itheima.commons.model.vo.TaohuaVo;


import com.itheima.dubbo.interfaces.TaohuaApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.time.Duration;
import java.util.List;


/**
 *
 */
@Service
public class TaohuaService {

    @Reference
    private TaohuaApi taohuaApi;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private OssTemplate ossTemplate;
    /**
     * 桃花传音-接收语音
     *
     * @return
     */
    public TaohuaVo queryVoice() {
        User user = UserThreadLocal.get();

        //创建redis键，接收语音每天只能10次
        String dateTime = DateUtil.today();

        //记录当天的接收次数
        String key = user.getId() + "_" + dateTime + "_GET_VOICE";
        //判断接收语音的次数
        String value = redisTemplate.opsForValue().get(key);
        if (value == null) {
            redisTemplate.opsForValue().set(key, "10", Duration.ofDays(1));
        } else if (value.equals(0)) {
            return null;
        }
        redisTemplate.opsForValue().decrement(key);

        //获取所有语音的集合
        List<Voice> voices = taohuaApi.queryVoices();

        //获取非当前用户的语音
        Voice voice = createVoiceUserId(voices, userInfoService.findUserInfoByUserId(user.getId()));
        UserInfo userInfo = userInfoService.findUserInfoByUserId(voice.getUserId());

        //拼凑vo对象
        TaohuaVo taohuaVo = new TaohuaVo();
        taohuaVo.setId(Convert.toInt(voice.getUserId()));
        taohuaVo.setAvatar(userInfo.getLogo());
        taohuaVo.setNickname(userInfo.getNickName());
        taohuaVo.setGender(userInfo.getSex() == 1 ? "man" : "woman");
        taohuaVo.setAge(userInfo.getAge());
        taohuaVo.setSoundUrl(voice.getSoundUrl());

        Integer count = Convert.toInt(redisTemplate.opsForValue().get(key));

        taohuaVo.setRemainingTimes(count);

        return taohuaVo;
    }


    /**
     * 随机获取一个非当前用户的语音
     *
     * @param voices
     * @param userInfo
     * @return
     */
    private Voice createVoiceUserId(List<Voice> voices, UserInfo userInfo) {
        //获取语音集合里面的任意一个
        Voice voice = voices.get(RandomUtil.randomInt(0, voices.size() - 1));

        //判断非自己,异性,不重复的语音
        String sex = userInfo.getSex() == 1 ? "man" : "woman";
        if (voice.getUserId() == userInfo.getUserId() || voice.getGender().equals(sex)) {
            //判断redis里面是否已经存在这个语音地址
            if (!redisTemplate.opsForHash().hasKey("voice", voice.getSoundUrl())) {
                redisTemplate.opsForHash().put("voice", voice.getSoundUrl(), "0");
                return voice;
            }else if(redisTemplate.opsForHash().hasKey("voice", voice.getSoundUrl())){
                createVoiceUserId(voices, userInfo);
            }
        }
        redisTemplate.opsForHash().put("voice", voice.getSoundUrl(), "0");
        return voice;
    }

    /**
     * 发送语音
     *
     * @param soundFile
     * @return
     */
    public boolean saveVoice(MultipartFile soundFile) {
        User user = UserThreadLocal.get();
        //创建redis键(每天只能传音10次)
        //根据当天的时间设置，并且根据下面的清除缓存设置清除
        String today = DateUtil.today();
        //记录当天的发送次数
        String key = user.getId()+"_"+today+"_SEND_VOICE";

        String Value = redisTemplate.opsForValue().get(key);
        if(Value==null){
            redisTemplate.opsForValue().set(key,"10",Duration.ofDays(1));
        }else if(Value.equals(0)){
            return false;
        }
        redisTemplate.opsForValue().decrement(key);

        UserInfo userInfo = this.userInfoService.findUserInfoByUserId(user.getId());
        Voice voice = new Voice();
        voice.setUserId(userInfo.getUserId());
        voice.setGender(userInfo.getSex() == 1 ? "man" : "woman");

        

        try {
            String url = ossTemplate.uploadPicture(soundFile.getBytes(), soundFile.getOriginalFilename());
            voice.setSoundUrl(url);
            taohuaApi.saveVoice(voice);
            return true;
        } catch (Exception e) {
            throw new MyException(ErrorResult.sendVoiceFile());
        }
    }
}
